package com.carlife.algorithm;

import com.carlife.util.Constants;

import android.util.Log;

/**
 * 直线拟合法
 * y = a + bx
 * 
 * (1)aN + bSum(x) = Sum(y)
 * (2)aSum(x) + bSum(xx) = Sum(xy)
 * =>
 *  a = [Sum(x)Sum(xy) - Sum(xx)Sum(y)]/[Sum(x)Sum(x)-NSum(xx)]
 *  b = [NSum(xy)- Sum(x)Sum(y)]/[NSum(xx)-Sum(x)Sum(x)]
 * 
 * @author luyuan
 *
 */
public class StraitLineFitting implements Fitting {
	
	private double d_x[] = null;
	private double d_y[] = null;

	private int number = 0;
	private double sum_x = 0;
	private double sum_y = 0;
	private double sum_xx = 0;
	private double sum_xy = 0;
	
	private double paramA = 0;
	private double paramB = 0;
	
	@Override
	public double fittingY(double x) {
		double y = paramA + paramB*x;
		Log.d(Constants.LOG_TAG, "X = " + x + ", Y = " + y);
		return y;
	}

	@Override
	public void initial(double[] discreteData_x, double[] discreteData_y ) {
		if (discreteData_x.length != discreteData_y.length) {
			throw new IllegalArgumentException("x,y have difference data number!");
		}
		
		this.number = discreteData_x.length;
		
		for (int i = 0; i < discreteData_x.length; i++) {
			sum_x += discreteData_x[i];
			sum_xx += discreteData_x[i]*discreteData_x[i];
			sum_y += discreteData_y[i];
			sum_xy += discreteData_x[i]*discreteData_y[i];
		}
		
		paramA = (sum_x*sum_xy - sum_xx*sum_y)/(sum_x*sum_x-number*sum_xx); 
		paramB = (number*sum_xy-sum_x*sum_y)/(number*sum_xx-sum_x*sum_x);
		System.out.println("A=" + paramA + ", B=" + paramB);
	}
	
	public static void main(String [] args) {
		StraitLineFitting fitting = new StraitLineFitting();
		fitting.initial(new double[]{1,2,3,4,5,6,7,8,9,10}, new double[]{10,20,30,40,50,60,70,80,90,100});
		fitting.initial(new double[]{165,123,150,123,141}, new double[]{187,126,172,125,148});
		System.out.println("x = 2.2, y = " + fitting.fittingY(2.2));
		
	}

}

